package com.yunduansing.core.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yunduansing.core.commons.DbCommon;
import com.yunduansing.core.dto.BaseSearch;
import com.yunduansing.core.dto.GroupDto;
import com.yunduansing.core.model.GroupModel;
import com.yunduansing.core.service.GroupService;
import com.yunduansing.core.service.RoleService;
import com.yunduansing.core.utils.CommonUtil;

@Controller
@RequestMapping("/manager/group")
public class GroupController {
	@Autowired
	private GroupService service;
	@Autowired
	private RoleService roleService;
	
	@RequestMapping(value="/index")
	public String index(){
		return "/beetl/group/index";
	}
	
	@ResponseBody
	@RequestMapping(value="/page",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	public String pagination(DbCommon.Grid grid,BaseSearch search){
		return CommonUtil.toJsonWithGson(service.pagination(grid, search));
	}
	
	@RequestMapping(value="/detail",method=RequestMethod.GET)
	public ModelAndView detail(Model model,@RequestParam(value="id",required=false) Integer id){
		ModelAndView view=new ModelAndView();
		view.setViewName("/beetl/group/detail");
		GroupDto group;
		if(id!=null)
			group=service.getGroupWithRolesById(id);
		else
			group=new GroupDto();
		model.addAttribute("model", group);
		model.addAttribute("roleList", roleService.getAll());
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value="/save",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	public String save(GroupModel group,@RequestParam(value="roleIds[]",required=false) List<Integer> roleIds){
		return CommonUtil.toJsonWithGson(service.saveWithRoles(group, roleIds));
	}
	
	@ResponseBody
	@RequestMapping(value="/delete",method=RequestMethod.POST,produces="application/json;charset=utf-8")
	public String delete(@RequestParam(value="ids[]") List<Object> ids){
		return CommonUtil.toJsonWithGson(service.deleteByKeys(ids));
	}
}
